import mysql.connector
import requests
import time
from concurrent.futures import ThreadPoolExecutor, as_completed

# 数据库配置
db_config = {
    'host': '47.92.162.251',
    'port': 3306,
    'user': 'remote_user',
    'password': 'liYC060214pp',
    'database': 'expert_miniapp_db'
}

def get_demands_without_summary():
    """获取所有没有summary的需求ID"""
    conn = mysql.connector.connect(**db_config)
    cursor = conn.cursor()
    cursor.execute("SELECT demand_id FROM demand WHERE summary IS NULL OR summary = ''")
    demand_ids = [row[0] for row in cursor.fetchall()]
    cursor.close()
    conn.close()
    return demand_ids

def generate_summary(demand_id):
    """为单个需求生成summary"""
    url = f"http://localhost:8080/api/demands/{demand_id}/regenerate-summary"
    headers = {'Content-Type': 'application/json'}

    try:
        response = requests.post(url, headers=headers, timeout=60)
        if response.status_code == 200:
            return demand_id, True, "OK"
        else:
            return demand_id, False, f"HTTP {response.status_code}"
    except Exception as e:
        return demand_id, False, str(e)[:50]

def main():
    print("Fetching demands without summary...")
    demand_ids = get_demands_without_summary()
    total = len(demand_ids)
    print(f"Found {total} demands to process")

    if total == 0:
        print("All demands have summaries!")
        return

    print(f"\nStarting batch generation with 10 concurrent threads...")

    success_count = 0
    fail_count = 0
    start_time = time.time()

    # 使用线程池并发处理,最多10个线程
    with ThreadPoolExecutor(max_workers=10) as executor:
        futures = {executor.submit(generate_summary, did): did for did in demand_ids}

        for i, future in enumerate(as_completed(futures), 1):
            demand_id, success, msg = future.result()
            if success:
                success_count += 1
                status = "SUCCESS"
            else:
                fail_count += 1
                status = "FAIL"

            print(f"[{i}/{total}] {status} {demand_id[:8]}... - {msg}")

            # 每处理10个休息1秒,避免过载
            if i % 10 == 0:
                time.sleep(1)

    elapsed = time.time() - start_time
    print(f"\nDone! Success: {success_count}, Fail: {fail_count}, Time: {elapsed:.1f}s")

if __name__ == "__main__":
    main()
